package com.wiley.publicMethod;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import io.appium.java_client.android.AndroidDriver;

/**
 * 封装webdriver的底层方法
 */

public class BasePage {

	public AndroidDriver driver;
	public static final String BaseId = "com.haodou.recipe:id/";

	//初始化apk配置
	public DesiredCapabilities SetCap() {
		DesiredCapabilities capabilities = new DesiredCapabilities();
		capabilities.setCapability("deviceName", "xiaomi");
		capabilities.setCapability("appPackage", "com.haodou.recipe");
		capabilities.setCapability("appActivity", "com.haodou.recipe.Main");
		capabilities.setCapability("unicodeKeyboard", "True");
		capabilities.setCapability("resetKeyboard", "True");
		capabilities.setCapability("noSign", "True");
		return capabilities;
	}

	//初始化driver
	public AndroidDriver SetDriver() throws MalformedURLException {
		try{
			driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), this.SetCap());
		}catch (MalformedURLException e){
			e.printStackTrace();
		}
		return driver;
	}

	//封装智能等待方法
	private boolean waitToDisplayed(final By loc) {
		boolean waitDisplayed=false;
		try {
			waitDisplayed = new WebDriverWait(driver, 10)
					.until(new ExpectedCondition<Boolean>() {
						public Boolean apply(WebDriver d) {
							return d.findElement(loc).isDisplayed();
						}
					});
		} catch (NoSuchElementException e) {
			System.err.println("元素"+loc.toString()+"找不到");
		}
		return waitDisplayed;
	}
	
	//定位单个元素方法
	protected WebElement findEle(By loc){
		WebElement ele = null;
		if(this.waitToDisplayed(loc)){
			ele = driver.findElement(loc);
		}
		return ele;
	}

	//判断元素是否出现
	public boolean isElementPresent(By loc){
		boolean isDisplayed = false;
		try{
			isDisplayed = this.findEle(loc).isDisplayed();
		}catch(Exception e){
			isDisplayed = false;
		}
		return isDisplayed;
	}
	
	//定位一组元素方法
	public List<WebElement> findEles(By loc){
		List<WebElement> eles = null;
		if (this.waitToDisplayed(loc)) {
			eles = driver.findElements(loc);
		}
		return eles;
	}

	//点击一个元素
	public void clickEle(By loc){
		WebElement ele = this.findEle(loc);
		ele.click();
	}

	//获取元素集长度
	public int getElesLength(By loc){
		List<WebElement> eles = this.findEles(loc);
		return eles.size();
	}
	
	//点击一组元素中的任一个的方法
	public void clickEles(By loc,int i){
		List<WebElement> eles = this.findEles(loc);
		eles.get(i).click();
	}

	//输入方法
	public void sendKeys(By loc,String value){
		this.findEle(loc).clear();
		this.findEle(loc).click();
		this.findEle(loc).sendKeys(value);
	}
	
	public void sendKeysByIndex(By loc, int index, String value) {
		WebElement ele = this.findEles(loc).get(index);
		ele.clear();
		ele.click();
		ele.sendKeys(value);
	}
	
	public void swipeOpt(By loc ,String text, boolean up){
		WebElement ele = this.findEle(loc);
		Point local = ele.getLocation();
		while(true){
			try {
				if(driver.getPageSource().contains(text)){
					break;
				}
			} catch (Exception e) {
				if(up){
					driver.swipe(local.getX(), local.getY(), local.getX(), local.getY()-30, 500);
				}else{
					driver.swipe(local.getX(), local.getY(), local.getX(), local.getY()+30, 500);
				}
			}
		}
	}
	
	//获取屏幕占应用大小
	public int[] appScreen(){
		int width=driver.manage().window().getSize().getWidth();
		int heightScreen=driver.manage().window().getSize().getHeight();
		int[] appWidthAndHeight={width,heightScreen};
		return appWidthAndHeight;
	}
	
	//向上滑动
	public void swipeToUp(int duration){
		int startY=this.appScreen()[1]*4/5;
		int endY=this.appScreen()[1]*1/5;
		int x=this.appScreen()[0]*1/2;
		try{
			driver.swipe(x,startY,x,endY,duration);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//webview
	public boolean switchToWebview(){
        try {
            Set<String> contexts = driver.getContextHandles();
            for (String s : contexts) {
                if (s.contains("WEBVIEW")) {
                    driver.context(s);
                    return true;
                }
            }
            return false;
        } catch (WebDriverException e) {
            System.out.println("Error: catch WebDriverException.");
            e.printStackTrace();
            return false;
        }
	}
	
	//获取当前日期
	public static String getCurrentDateTime(){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		return df.format(new Date());
	}

	//获取脚本名字
	public String getName(String name){
		String date = getCurrentDateTime();
		String fp = "./src/main/java/com/wiley/result/" + date + "/image/";
		String type = ".png";
		String filename = fp+"\\"+name+type;
		File file = new File(fp);
		if(!file.exists()){
			file.mkdir();
		}else{
			file = new File("./src/main/java/com/wiley/result/" + filename);
			if(!file.exists()){
				file.mkdir();
			}
		}
		return filename;
	}

	//截图方法
	public void captureScreen(String name){
		File screenShotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE );
		String filename = this.getName(name);
		try {
			FileUtils.copyFile (screenShotFile, new File(filename));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//打Log方法
	public LoggerControler MyLogger(Class name){
		return LoggerControler.getLogger(name);
	}
}

